<?php

namespace App\Http\Controllers\Sdk;

use App\Http\Controllers\Controller;
use App\Models\CommodityActivity;
use App\Services\Commodity;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class CommodityController extends Controller
{
    public function list(Request $request)
    {
        {
            $paginate = Commodity::getActivityListWithCache($request, $request->get('type', CommodityActivity::TYPE_LIVE_TODAY));

            $paginate['data'] = array_map(function ($item) {
                $item['countdown'] = Carbon::now()->diffInMilliseconds($item['panic_buying_end_time']);
                [$item['earn'], $item['price'], $item['retail_price']] = Commodity::getPriceFromSkuListByIdentity($item['skus']);

                // 最大最小 价格范围
                $priceList = array_column($item['skus'], 'external_guide_price');
                $item['min_price'] = min($priceList);
                $item['max_price'] = max($priceList);

                return $item;
            }, $paginate['data'] ?? []);

            return $this->response->array($paginate);
        }
    }

    public function info($id)
    {
        $commodity = CommodityActivity::query()
            ->with([
                'materials.attachments',
                'attributes' => fn ($builder) => $builder->with(['values.attachments']),
                'attachments',
                'commodity.attachments',
                'skus' => fn ($builder) => $builder->with(['values', 'attachments'])
            ])
            ->findOrFail($id)
            ->toArray();

        $currentLevelIdentity = Auth::user()->currentLevelIdentity()['id'];
        $priceList = array_column($commodity['skus'], 'external_guide_price');
        $commodity['min_price'] = min($priceList);
        $commodity['max_price'] = max($priceList);
        $commodity['countdown'] = Carbon::now()->diffInMilliseconds($commodity['panic_buying_end_time']);

        // 组装前端的 SKU 数据
        // 规格
        $sku = [
            'tree' => [],
            'list' => []
        ];
        foreach ($commodity['attributes'] as $index => $attribute) {
            $index ++;

            $sku['tree'][] = [
                'k' => $attribute['name'],
                'v' => array_map(
                    function ($value) {
                        $attachments = [];
                        if (!empty($value['attachments'])) {
                            $attachments = ['imgUrl' => $value['attachments'][0]['url'], 'previewImgUrl' => $value['attachments'][0]['url']];
                        }
                        return array_merge(['id' => $value['id'], 'name' => $value['content']], $attachments);
                    },
                    $attribute['values']
                ),
                'k_s' => 's' . $index,
                'attribute_id' => $attribute['id']
            ];
        }
        // SKU 值
        $tempSkuTree = arrayCombineByKey($sku['tree'], 'attribute_id');
        foreach ($commodity['skus'] as $index => $skuItem) {
            $skuItem['stock_num'] = $skuItem['stock']; // 库存
            foreach ($skuItem['values'] as $valueItem) { // 规格的值
                $skuItem[$tempSkuTree[$valueItem['attribute_id']]['k_s']] = (string) $valueItem['id'];
            }
            $skuItem['price'] = $skuItem[$currentLevelIdentity . '_price']; // (身份) 售价
            $skuItem['earn'] = $skuItem['external_guide_price'] - $skuItem['price']; // (身份) 售价
            $skuItem['earn'] = $skuItem['earn'] < 0 ? 0 : $skuItem['earn']; // 小于零 按照 零为准
            $sku['list'][] = $skuItem;
        }
        $sku['stock_num'] = array_sum(array_column($commodity['skus'], 'stock')); // 库存总数
        $sku['price'] = $commodity['min_price'] / 100; // 默认价格 (最小值) (单位 元, 这里给前端格式化好)
        $commodity['sku'] = $sku;

        return $this->response->array($commodity);
    }
}
